/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.web;

import cz.muni.fi.pa165.portalnahouby.api.dto.PickerDTO;
import cz.muni.fi.pa165.portalnahouby.api.serviceinterface.PickerService;
import cz.muni.fi.pa165.portalnahouby.implementation.util.Crypto;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.springframework.orm.jpa.JpaSystemException;

/**
 *
 * @author Lukas Marica
 */
@UrlBinding("/pickers/{$event}/{picker.id}")
public class PickerActionBean implements ActionBean {

    private ActionBeanContext context;

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }
    @SpringBean
    private PickerService service;

    @DefaultHandler
    public Resolution all() {
        return new ForwardResolution("/picker.jsp");
    }

    public List<PickerDTO> getPickers() {
        List<PickerDTO> result = service.getAllPickers();
        return result;
    }
    @ValidateNestedProperties(value = {
        @Validate(on = {"add", "save"}, field = "name", required = true, maxlength = 255),
        @Validate(on = {"add", "save"}, field = "surname", required = true, maxlength = 255),
        @Validate(on = {"add", "save"}, field = "pass", required = true, maxlength = 255),
        @Validate(on = {"add", "save"}, field = "login", required = true, maxlength = 255),
        @Validate(on = {"add", "save"}, field = "info", maxlength = 255)
    })
    private PickerDTO picker;

    public PickerDTO getPicker() {
        return picker;
    }

    public void setPicker(PickerDTO picker) {
        this.picker = picker;
    }

    @RequiresAdmin
    public Resolution add() throws NoSuchAlgorithmException, UnsupportedEncodingException {
        try {
        if (picker.getIsAdmin() == null) {
            picker.setIsAdmin(false);
        }
        picker.setPass(Crypto.encode(picker.getPass()));
        service.addPicker(picker);
        picker.setPass("");
        } catch (JpaSystemException jse) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("name", new LocalizableError("picker.duplicity"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void loadPickerFromDatabase() {
        String ids = context.getRequest().getParameter("picker.id");
        if (ids == null) {
            return;
        }
        picker = service.findPicker(Long.parseLong(ids));
	picker.setPass("");
    }

	public Resolution edit() {
		SecurityActionBean securityActionBean = new SecurityActionBean();
		securityActionBean.setContext(getContext());
		if( securityActionBean.isCurrentUserID(picker.getId()))
		{
			return new ForwardResolution("/pickeredit.jsp");
		}
		else
		{
			return new RedirectResolution("/not_enough_rights.jsp");
		}
	}

    public Resolution save()  throws NoSuchAlgorithmException, UnsupportedEncodingException {
        try {
        if (picker.getIsAdmin() == null) {
            picker.setIsAdmin(false);
        }
	if( picker.getPass() != null && ! picker.getPass().isEmpty())
	{
        picker.setPass(Crypto.encode(picker.getPass()));
	}
        service.editPicker(picker);
        picker.setPass("");
        } catch (JpaSystemException jse) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("name", new LocalizableError("picker.duplicity"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }

    @RequiresAdmin
    public Resolution delete() {
        try {
            service.deletePicker(picker.getId());

        } catch (JpaSystemException jse) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("name", new LocalizableError("picker.hasVisit"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }
}